<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <ul class="search-list" v-show="keyword">
      <div>
        <li class="item border-bottom" v-for="item in searchResults" :key="item.id"  @click="changeCurrCity">{{item.name}}</li>
      </div>
      <div class="item border-bottom" v-show="noSearchShow">没有搜索到匹配结果</div>
    </ul>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapActions} from 'vuex'
export default {
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      searchResults: [],
      noSearchShow: false
    }
  },
  methods: {
    ...mapActions(['changeCity']),
    changeCurrCity (e) {
      // console.log(e.target.innerText)
      // this.$store.dispatch('changeCity', e.target.innerText)
      this.changeCity(e.target.innerText)
      this.$router.push('/')
      this.keyword = ''
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.keyword) {
        this.noSearchShow = false
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.cities) {
            this.cities[i].forEach(item => {
              if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
                result.push(item)
              }
            })
          }
          this.searchResults = result
          if (!result.length) {
            this.noSearchShow = true
          } else {
            this.noSearchShow = false
          }
        }, 1000)
      } else {
        this.searchResults = []
      }
    }
  },
  updated () {
    if (this.keyword) {
      this.scroll = new BScroll('.search-list', {
        click: true
      })
    }
  }
}
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>
  @import '~styles/varibles.styl'
  .border-bottom
    &:before
      border-color #bbb
  .search
    height .72rem
    padding 0 .15rem
    background $bgColor
    .search-input
      width 100%
      height .62rem
      line-height .62rem
      padding 0 .1rem
      box-sizing border-box
      border-radius .06rem
      text-align center
      color #777
  .search-list
    background #fff
    overflow hidden
    position absolute
    top 1.6rem
    bottom 0
    left 0
    right 0
    z-index 1
    .item
      line-height .54rem
      padding-left .2rem
</style>
